import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'

export interface Material {
  id: number
  name: string
  unit: string
}

export interface MaterialUsage {
  work_order_id: number
  material_id: number
  quantity: number
  usage_type: string
  purpose: string
}

export function useMaterials() {
  const availableMaterials = ref<Material[]>([])

  // 加载材料数据
  const loadMaterials = async () => {
    try {
      const response = await api.getMaterials({ per_page: 1000 })
      // 确保响应数据结构正确
      availableMaterials.value = response.data?.materials || response.data || []
    } catch (error) {
      console.error('加载材料失败:', error)
      // 确保在错误情况下也有默认值
      availableMaterials.value = []
    }
  }

  // 添加多个材料使用记录
  const addMultipleMaterialUsage = async (usages: MaterialUsage[]) => {
    try {
      await api.addMultipleMaterialUsage(usages)
    } catch (error) {
      console.error('添加材料使用记录失败:', error)
      throw error
    }
  }

  return {
    availableMaterials,
    loadMaterials,
    addMultipleMaterialUsage
  }
}